<template>
  <div>
    <el-dropdown-item style="text-align: center;padding: 0;">
      <el-tooltip placement="left" effect="dark">
        <div slot="content" style="max-width: 200px;">判断平台、账号与账号ID是否一致对资源进行修改（可新增)</div>
        <import-button
          v-if="hasRouteAuth('medium:operator:importAll')"
          ref="importButton"
          :import-api="'/admin/medium/importAll'"
          :btn-text="'导入新增(量小)'"
          :medium-btn-style="mediumBtnStyle"
          :is-medium="true"
          :medium-hidden-icon="true"
          class="btn"
          @beforeUpload="beforeUpload($event, 'importButton')"
          @onSucess="onSucess"
          @onError="onError('')"
          @onComplate="onComplate"
        />
      </el-tooltip>
    </el-dropdown-item>
    <el-dropdown-item style="text-align: center;padding: 0;">
      <import-button
        v-if="hasRouteAuth('medium:changeName:import')"
        ref="changeNameListImportButton"
        :import-api="'/admin/resource/changeNameList/import'"
        :btn-text="'导入改名记录'"
        :medium-btn-style="mediumBtnStyle"
        :is-medium="true"
        :medium-hidden-icon="true"
        :hide-confir="true"
        :hide-confirm="true"
        class="btn"
        @beforeUpload="beforeUpload($event, 'changeNameListImportButton')"
        @onSucess="onSucess"
        @onError="onError('')"
        @onComplate="onComplate"
      />
    </el-dropdown-item>
    <el-dropdown-item v-if="hasRouteAuth('medium:price:import')" style="text-align: center;padding: 0;">
      <NormalImportButton
        :get-list="onPriceUploadSuccess"
        import-api="/admin/resource/moneyData/import"
        accept=".xls,.xlsx"
        is-diy>
        <span style="font-size:14px;display:block;text-align:center;">导入上刊价格</span>
      </NormalImportButton>
    </el-dropdown-item>
    <el-dropdown-item style="text-align: center;padding: 0;">
      <el-tooltip placement="left" effect="dark">
        <div slot="content" style="max-width: 200px;">判断平台与系统ID对资源进行修改（不可新增）</div>
        <span v-if="hasRouteAuth('medium:operator:importEdit')" style="font-size:14px" @click="goUpload">导入编辑</span>
      </el-tooltip>
    </el-dropdown-item>
    <el-dropdown-item style="text-align: center;padding: 0;" divided>
      <export-button
        v-if="hasRouteAuth('medium:operator:exportAll')"
        ref="exportButton"
        :export-api="'/admin/medium/exportAll'"
        http-method="post"
        export-name="资源列表"
        is-diy
        is-before-export
        @beforeExport="beforeExport"
        @onSuccessExport="onSucess"
        @onErrorExport="onError"
        @onComplate="onComplate"
      >
        <div class="asyncUpload">全部导出</div>
      </export-button>
    </el-dropdown-item>
    <el-dropdown-item style="text-align: center;padding: 0;">
      <export-button
        v-if="hasRouteAuth('medium:changeName:export')"
        ref="changeNameExportButton"
        :export-api="'/admin/resource/changeNameList/export'"
        export-name="改名记录"
        http-method="post"
        is-before-export
        is-diy
        @beforeExport="beforeExportChangeName"
        @onErrorExport="onError"
      >
        <div class="asyncUpload">导出改名记录</div>
      </export-button>
    </el-dropdown-item>
    <template v-for="(i, index) in extendList">
      <template v-if="i.auth === undefined || i.auth">
        <el-dropdown-item v-if="i.type ==='export'" :key="index+'export'" :divided="i.divided" class="white-space-nowrap" @click.native="handelClick(i)">
          <export-button
            :ref="i.refName"
            :export-api="i.exportApi"
            :is-before-export="i.isBeforeExport || false"
            :export-name="i.exportName"
            :export-name-last="i.exportNameLast"
            :is-diy="true"
            :query-data="i.queryData || {}"
            :default-loading="false"
            :http-method="i.httpMethod || 'get'"
            @onComplate="exportonComplate($event,i)"
            @beforeExport="extendBeforeExport(i)" >
            <el-tooltip v-if="i.tip" placement="left" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ i.tip }}</div>
              <span style="font-size:14px;display:block;text-align:center;">
                <i v-if="loading" class="el-icon-loading"/>{{ i.label }}
              </span>
            </el-tooltip>
            <span v-else style="font-size:14px;display:block;text-align:center;">
              <i v-if="loading" class="el-icon-loading"/>{{ i.label }}
            </span>
          </export-button>
        </el-dropdown-item>
      </template>
    </template>
    <Progress
      ref="progress"
      :title="progressTitle"
      @cancelExportHttp="cancelExportHttp"
      @cancelImportHttp="cancelImportHttp"
    />
  </div>
</template>
<script>
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import axios from 'axios';
import { getToken } from '@/utils/auth';
import { showModal } from '@/utils/message';

import Progress from './Progress';
import ImportButton from './mediumImport/importAll';
import ExportButton from '@/components/ExportButton';
import NormalImportButton from '@/components/ImportButton';

import { isMediumUser, isMediumAdmin } from '@/utils/permission';

const {
  BASE_API
} = process.env;

export default {
  name: 'ImportNExport',
  components: { ImportButton, ExportButton, Progress, NormalImportButton },
  props: {
    getFilterParams: {
      type: Function,
      default: null
    },
    /**
     * label: 名称
     * handelClick: 点击事件
     * auth: 权限
     */
    extendList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      timer: '',
      mediumBtnStyle: {
        background: '#fff',
        color: '#333',
        fontSize: '13px',
        width: '100%',
        whiteSpace: 'nowrap',
        padding: '0',
        marginLeft: '0px',
        marginRight: '0px',
        height: '30px',
        lineHeight: '30px',
        border: 'none',
        borderRadius: '0'
      },
      progressTitle: '',
      loading: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isMediumUser() {
      return isMediumUser();
    }
  },
  methods: {
    isMediumAdmin,
    hasRouteAuth,
    // 导出excel前调用的方法
    beforeExport() {
      this.progressTitle = '导出数据';
      this.$refs.progress.tabMaskShow(1);
    },
    handelClick(i) {
      if (i.handelClick)i.handelClick();
    },
    extendBeforeExport(i) {
      if (i.beforeExport) i.beforeExport();
    },
    exportonComplate(data, i) {
      this.loading = false;
      if (i.exportonComplate) i.exportonComplate(data);
    },
    btnExport(params, refName) {
      if (this.$refs[refName]) {
        let msg = '<div>是否确定导出数据？</div>';
        if (!params.ids) {
          msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
        }
        showModal(msg, '', {
          iconClass: 'del-icon'
        }).then(() => {
          this.loading = true;
          this.$emit('beginExport');
          this.$refs[refName][0].btnExport(params);
        });
      }
    },
    async beforeExportChangeName() {
      let data = {};
      if (this.getFilterParams) {
        data = await this.getFilterParams();
      }
      let msg = '<div>是否确定导出数据？</div>';
      if (!data.ids) {
        msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
      }
      showModal(msg, '', {
        iconClass: 'del-icon',
        customClass: 'del-message del-message-cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning'
      }).then(() => {
        this.$refs.changeNameExportButton.btnExport(data);
      }).catch(() => {
        return false;
      });
    },
    beforeExportPriceTemplate() {
      this.$refs['priceExportBtnRef'].btnExport();
    },
    startExport() {
      const uploadId = this.createUploadId();
      const params = { uploadId, options: encodeURIComponent('[]') };
      this.$refs.progress.beforeUpload(params.uploadId);
      // // 开始请求
      this.$refs.exportButton.btnExport(params);
    },
    // 导入excel前调用的方法
    beforeUpload({ file }, refName = 'importButton') {
      this.progressTitle = '导入数据';
      this.$refs.progress.tabMaskShow(2);
      const uploadId = this.createUploadId();
      this.$refs[refName].setUploadId(uploadId);
      this.$refs.progress.beforeUpload(uploadId);
    },
    // 上传钩子
    onComplate(message) {
      this.$refs.progress.onComplate(message);
    },
    onSucess(message) {
      this.$refs.progress.onSucess(message);
      this.$emit('getMediumData');
    },
    onPriceUploadSuccess() {
      this.$emit('getMediumData');
    },
    onError(message) {
      this.$refs.progress.onError(message);
    },
    // 生成上传唯一标识，用于获取进度
    createUploadId() {
      const userId = this.userInfo.id;
      const timestamp = (new Date()).valueOf();
      return `${userId}${timestamp}`;
    },
    // 取消请求
    cancelImportHttp() {
      this.$refs.importButton.cancelHttp();
      this.$refs.changeNameListImportButton.cancelHttp();
    },
    cancelExportHttp() {
      this.$refs.exportButton.cancelHttp();
    },
    async template() {
      try {
        const service = axios.create({
          baseURL: BASE_API, // api 的 base_url
          timeout: 1800000, // 请求超时时间
          headers: {
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': 'attachment;filename=kpi.xlsx'
          }
        });
        this.serviceToken(service);
        const res = await service.get('/admin/medium/template', { responseType: 'blob' });
        const headers = res.headers;
        if (headers && headers['content-type'].indexOf('json') !== -1) {
          const a = new Blob([res.data]);
          const reader = new FileReader();
          reader.readAsText(a);
        } else {
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const a = document.createElement('a');
          a.style.display = 'none';
          a.setAttribute('download', `导入模板.xlsx`);
          a.setAttribute('href', url);
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 设置token
    serviceToken(service) {
      // request拦截器
      service.interceptors.request.use(
        config => {
          const token = this.$store.getters.token || getToken();
          if (token) {
            config.headers.common['token'] = token;
          }
          return config;
        },
        error => {
          console.log(error);
          Promise.reject(error);
        }
      );
    },
    goUpload() {
      this.$router.push({
        name: 'resourceupload',
        query: { type: '1', isImportEdit: true }
      });
    }
  }
};
</script>
<style scoped lang="scss">
.btn-container {
  display: flex;
  border-left: none;
  position: relative;
  .download-template {
    background-color: #eff3fb;
    padding-top: 0;
    border-radius: 4px;
    width:32px;
    height:32px;
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 32px;
      height: 32px;
    }
  }
  .batch-button {
    height:32px;
    background:rgba(239,243,251,1);
    border-radius:4px;
    border: none;
    color: #406EFF;
    padding: 0 12px;
  }
  .button-container {
    margin-left: 16px;
  }
}
.create-btn {
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
  margin-left: 16px;
  width:80px;
  height:32px;
  background:rgba(64,110,255,1);
  border-radius:4px;
  font-size:14px;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:500;
  color:rgba(255,255,255,1);
  line-height:14px;
}
.asyncUpload {
  font-size: 14px;
  width: 100%;
}
::v-deep {
  .el-dropdown-menu__item--divided:before {
    margin: 0;
  }
}
</style>
<style lang="scss">

</style>
